<template>
  <div>
    <PageWrapper :contentFullHeight="true" :contentBackground="true">
      <Row :gutter="24">
        <Col :xs="24" :sm="24" :md="24" :lg="4" :xl="4">
          <div style="overflow-y: scroll; overflow-x: hidden; height: 91vh">
            <BasicTree
              :treeData="treeData"
              :toolbar="true"
              :search="true"
              @select="selectTree"
              :beforeRightClick="rightClick"
            />
          </div>
        </Col>
        <Col :xs="24" :sm="24" :md="24" :lg="20" :xl="20">
          <!-- 表单模板显示 -->
          <BasicTable @register="registerTable" v-if="!isShow" />
          <!-- 表单详情显示 -->
          <Tabs v-model:activeKey="activeKey" @change="tabChange" v-else>
            <TabPane key="1" :tab="t('routes.table.formManagement.class')">
              <div
                style="
                  width: 40vw;
                  display: flex;
                  justify-content: center;
                  align-items: center;
                  margin-top: 20px;
                "
              >
                <Row>
                  <Col :span="24">
                    <BasicForm @register="registerForm" />
                  </Col>
                  <Col :span="24" style="display: flex; justify-content: flex-end">
                    <a-button
                      v-auth="['system:form:category:save']"
                      type="primary"
                      @click="handleSave"
                      >{{ t('common.saveText') }}</a-button
                    >
                  </Col>
                </Row>
              </div>
            </TabPane>
            <TabPane
              key="2"
              :tab="t('routes.table.formManagement.classProperty')"
              :disabled="isCreate"
            >
              <BasicTable @register="registerTable2">
                <template #toolbar>
                  <a-button
                    v-auth="['system:form:attribute:create']"
                    type="primary"
                    @click="handleClassCreate"
                  >
                    {{ t('common.create') }}
                  </a-button>
                </template>
                <!-- 控件 -->
                <template #attr="{ text: attr }">
                  {{ proxy.$filters.filterFormControlType(attr) }}
                </template>
                <!-- 是否允许为空 -->
                <template #pdmnull="{ text: pdmnull }">
                  {{ pdmnull === '1' ? t('common.yes') : t('common.no') }}
                </template>
                <!-- 是否为敏感属性 -->
                <template #isOnly="{ text: isOnly }">
                  {{ isOnly === '1' ? t('common.yes') : t('common.no') }}
                </template>
                <template #action="{ record }">
                  <TableAction
                    :actions="[
                      {
                        icon: 'clarity:note-edit-line',
                        onClick: handleClassEdit.bind(null, record),
                        auth: 'system:form:attribute:update',
                      },
                      {
                        icon: 'ant-design:delete-outlined',
                        color: 'error',
                        popConfirm: {
                          title: t('common.confirmDelete'),
                          confirm: handleClassDelete.bind(null, record),
                        },
                        auth: 'system:form:attribute:delete',
                      },
                    ]"
                  />
                </template>
              </BasicTable>
            </TabPane>
            <TabPane
              key="3"
              :tab="t('routes.table.formManagement.documentTemplate')"
              :disabled="isCreate"
            >
              <Row>
                <Col :span="24">
                  <iframe
                    :src="previewSrc"
                    frameborder="0"
                    style="width: 100%; height: 600px; border: 1px solid #ddd; border-radius: 8px"
                  ></iframe>
                </Col>
              </Row>

              <Row style="margin-top: 20px; text-align: right">
                <Col :span="24" style="display: flex; justify-content: flex-end; gap: 12px">
                  <Upload :customRequest="customUpload" :beforeUpload="beforeUpload">
                    <a-button
                      v-auth="['system:form:template:upload']"
                      type="primary"
                      preIcon="ion:cloud-upload-outline"
                    >
                      {{ t('common.upload') }}
                    </a-button>
                  </Upload>

                  <a-button
                    v-auth="['system:form:template:download']"
                    preIcon="ion:download-outline"
                    type="primary"
                    @click="download"
                  >
                    {{ t('common.download') }}
                  </a-button>

                  <a-button
                    v-auth="['system:form:template:delete']"
                    color="error"
                    preIcon="ion:trash-outline"
                    @click="handleDelete"
                  >
                    {{ t('common.delete') }}
                  </a-button>
                </Col>
              </Row>
            </TabPane>
            <TabPane
              key="4"
              :tab="t('routes.table.formManagement.typeBinding')"
              :disabled="isCreate"
            >
              <div style="width: 50vw; display: flex; align-items: center; margin-top: 20px">
                <Row>
                  <Col :span="24">
                    <Transfer
                      :titles="[
                        t('routes.demo.FigureDocSettings.unboundAssociatedGraphicsType'),
                        t('routes.demo.FigureDocSettings.boundAssociatedGraphicsType'),
                      ]"
                      :listStyle="{ width: '250px', height: '300px' }"
                      :dataSource="unBingList"
                      :targetKeys="bingList"
                      :render="(item) => item.title"
                      @change="handleChange"
                    />
                  </Col>
                </Row>
                <Row>
                  <Col
                    :span="24"
                    style="
                      display: flex;
                      justify-content: flex-end;
                      margin-top: 20px;
                      margin-left: -30px;
                    "
                  >
                    <a-button
                      v-auth="['system:form:type:save']"
                      type="primary"
                      @click="handleSave2"
                      >{{ t('common.saveText') }}</a-button
                    >
                  </Col>
                </Row>
              </div>
            </TabPane>
          </Tabs>
        </Col>
      </Row>
      <!-- 新增类属性 -->
      <formClassProp @register="registerClassPropModal" @success="reload2" />
      <!-- 属性组定义 -->
      <attrGroup @register="registerAttrGroupModal" />
      <!-- 属性页定义 -->
      <attrDefine @register="registerAttrDefineModal" />
    </PageWrapper>
  </div>
</template>

<script lang="ts" setup>
  import { ref, getCurrentInstance, onMounted, nextTick } from 'vue';
  import { Row, Col, Tabs, TabPane, Upload, Divider, Transfer } from 'ant-design-vue';
  import { PageWrapper } from '/@/components/Page';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { BasicForm, useForm } from '/@/components/Form';
  import { useModal } from '/@/components/Modal';
  import { BasicTree } from '/@/components/Tree/index';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { Base64 } from 'js-base64';

  import { getFormSettingColumns, getFormSetProperty, getClassColumns } from './data';

  import {
    downloadDocTypeTemplate,
    deleteDocTypeData,
    addDocTypeDataList,
    GetDocFileTemplateUrl,
    GetAllBdDocType,
    GetAllBdTree,
    getFileTypeTable,
    addFileTypeTable,
    updateDocTypeBase,
    getNoBdDocType,
    updateBingDocType,
    deleteDocType,
  } from '/@/api/demo/system';

  import formClassProp from './formClassProp.vue';
  import attrGroup from './attrGroup.vue';
  import attrDefine from './attrDefine.vue';

  const { proxy }: any = getCurrentInstance();
  const { t } = useI18n();
  const { createMessage } = useMessage();
  const treeData = ref([]);
  const isShow = ref(false);
  const activeKey = ref('1');
  const isUpdate = ref(false);
  const formTypeId = ref('');
  const previewSrc = ref('');
  const unBingList = ref([]);
  const bingList = ref([]);
  const isCreate = ref(false);
  const getClassId = ref('');

  const reloadTree = () => {
    GetAllBdTree().then((res) => {
      treeData.value = res;
    });
  };
  onMounted(() => {
    // 表单类型表数据左侧树形结构
    reloadTree();
  });

  const rightClick = (node) => {
    const arr = [
      {
        label: t('routes.table.formManagement.newDocumentTemplate'),
        handler: () => {
          isShow.value = true;
          isCreate.value = true;
          isUpdate.value = false;
          resetFields();
        },
      },
      {
        label: t('routes.table.formManagement.formProperty'),
        handler: () => {
          openAttrDefineModal(true, { treeKey: node.eventKey });
        },
      },
      {
        label: t('routes.table.formManagement.formPropertyGroup'),
        handler: () => {
          openAttrGroupModal(true, { treeKey: node.eventKey });
        },
      },
    ];
    const arr2 = [
      {
        label: t('common.delText'),
        handler: () => {
          deleteDocTypeData(node.eventKey).then((res) => {
            if (res) {
              reloadTree();
              reload1();
              createMessage.success(t('common.delSuccessText'));
            }
          });
        },
      },
    ];
    if (node.eventKey === '-999') {
      return arr;
    } else {
      return arr2;
    }
  };

  const selectTree = (keys: string[]) => {
    // 将表单模板id存储到localStorage
    localStorage.setItem('BdGroupNameID', keys[0]);
    formTypeId.value = keys[0];
    if (keys.length > 0 && keys[0] !== '-999') {
      isUpdate.value = true;
      // 表单详情
      getFileTypeTable(formTypeId.value).then((res) => {
        const params = {
          oId: res.docMaindto.oId,
          name: res.docMaindto.name,
          template: 'none',
          counterID: res.docMaindto.counterID === '' ? null : res.docMaindto.counterID,
          createSoft: res.docMaindto.createSoft,
          datavault: res.docMaindto.datavault === 'pdmBinVault' ? '' : res.docMaindto.datavault,
          check1: res.docMaindto.dataType.split('')[7] == 1 ? true : false,
          check2: res.docMaindto.dataType.split('')[6] == 1 ? true : false,
          check3: res.docMaindto.dataType.split('')[2] == 1 ? true : false,
          check4: res.docMaindto.dataType.split('')[3] == 1 ? true : false,
          check5: res.docMaindto.dataType.split('')[1] == 1 ? true : false,
          check6: res.docMaindto.dataType.split('')[0] == 1 ? true : false,
          sourceFileStorageWay:
            res.docMaindto.datavault === '' || res.docMaindto.datavault === 'pdmBinVault'
              ? '0'
              : '1',
        };
        setFieldsValue(params);
      });
      // 类属性
      getClassId.value = formTypeId.value;
      reload2();
      isShow.value = true;
      isCreate.value = false;
      activeKey.value = '1';
    } else {
      // 表单模板
      isShow.value = false;
      activeKey.value = '1';
    }
  };

  // tabs切换
  const tabChange = (activeKey) => {
    if (activeKey === '3') {
      handlePreview();
    } else if (activeKey === '4') {
      getNoBdDocType(formTypeId.value).then((res) => {
        unBingList.value = res.allBingList === null ? [] : res.allBingList;
        bingList.value = res.bingList === null ? [] : res.bingList.map((item) => item.key);
      });
    }
  };

  // 保存
  const handleSave = async () => {
    const values = await validate();
    const newArr = [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0];
    newArr[7] = values.check1 ? 1 : 0;
    newArr[6] = values.check2 ? 1 : 0;
    newArr[2] = values.check3 ? 1 : 0;
    newArr[3] = values.check4 ? 1 : 0;
    newArr[1] = values.check5 ? 1 : 0;
    newArr[0] = values.check6 ? 1 : 0;

    const params = {
      oId: values.oId,
      name: values.name,
      template: 'none',
      counterID: values.counterID,
      createSoft: values.createSoft,
      datavault: values.datavault,
      dataType: newArr.join(''),
    };
    if (isUpdate.value) {
      // 修改
      await updateDocTypeBase(params);
      createMessage.success(t('common.saveSuccess'));
      isShow.value = true;
      isCreate.value = false;
      reloadTree();
      reload1();
    } else {
      await addFileTypeTable(params);
      createMessage.success(t('common.saveSuccess'));
      reloadTree();
      isShow.value = false;
      reload1();
    }
  };

  // 类属性新增
  const handleClassCreate = () => {
    openClassPropModal(true, {
      isUpdate: false,
      docTypeId: getClassId.value,
      newIndex:
        getDataSource2() === undefined
          ? 0
          : Number(getDataSource2()[getDataSource2().length - 1].dispIndex) + 1,
      tableData: getDataSource2(),
    });
  };

  // 类属性修改
  const handleClassEdit = (record: Recordable) => {
    openClassPropModal(true, {
      isUpdate: true,
      record: record,
      docTypeId: getClassId.value,
      tableData: getDataSource2(),
    });
  };

  // 类属性删除
  const handleClassDelete = (record: Recordable) => {
    if (record.canChange === '0') {
      createMessage.warning(t('routes.table.formManagement.baseProperty'));
    } else {
      deleteDocType(record.docTypeId, record.prop, record.dispIndex).then((res) => {
        if (res) {
          createMessage.success(t('common.delSuccessText'));
          reload2();
        }
      });
    }
  };

  // 下载
  const download = () => {
    downloadDocTypeTemplate(formTypeId.value).then((res) => {
      if (res) {
        createMessage.success(t('common.downLoadSuccess'));
      }
    });
  };

  // 删除
  const handleDelete = () => {
    deleteDocTypeData(formTypeId.value).then((res) => {
      if (res) {
        previewSrc.value = '';
        createMessage.success(t('common.delSuccessText'));
      }
    });
  };

  // 文件上传
  const customUpload = (e: any) => {
    const formData = new FormData();
    formData.append('file', e.file);
    addDocTypeDataList(formTypeId.value, formData).then((res) => {
      if (res) {
        nextTick(() => {
          handlePreview();
        });
        createMessage.success(t('common.uploadSuccess'));
      }
    });
  };

  const handlePreview = () => {
    GetDocFileTemplateUrl(formTypeId.value).then((res) => {
      let url = `${res[1]}:8012/onlinePreview?url=` + encodeURIComponent(Base64.encode(res[0]));
      previewSrc.value = url;
    });
  };

  // 文件上传前
  const beforeUpload = (file: any) => {
    // 只允许上传doc,docx,xls,xlsx文件类型
    const fileType = [
      'application/msword',
      'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
      'application/vnd.ms-excel',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    ].includes(file.type);
    if (!fileType) {
      createMessage.error(t('routes.demo.FigureDocSettings.uploadFileTypeError'));
    }
    return fileType;
  };

  const handleChange = (nextTargetKeys: string[]) => {
    bingList.value = nextTargetKeys;
  };

  // 类型绑定保存
  const handleSave2 = () => {
    const filteredData = unBingList.value.filter((item) => bingList.value.includes(item.key));
    updateBingDocType(formTypeId.value, filteredData).then((res) => {
      if (res) {
        createMessage.success(t('common.saveSuccess'));
      }
    });
  };

  // 初始化表格
  const [registerTable, { reload: reload1 }] = useTable({
    titleHelpMessage: 'formIndex',
    api: GetAllBdDocType,
    columns: getFormSettingColumns(),
    bordered: true,
    showIndexColumn: false,
    showTableSetting: true, // 显示表格设置工具
    tableSetting: { fullScreen: true }, // 表格设置工具配置
    canResize: false,
    rowKey: 'id',
  });

  // 属性详情
  const [registerForm, { validate, setFieldsValue, resetFields }] = useForm({
    labelCol: { span: 6 },
    wrapperCol: { span: 18 },
    schemas: getFormSetProperty(isUpdate),
    showResetButton: false,
    showSubmitButton: false,
  });

  // 初始化类属性表格
  const [registerTable2, { getDataSource: getDataSource2, reload: reload2 }] = useTable({
    titleHelpMessage: 'formClass',
    api: getFileTypeTable,
    beforeFetch: () => {
      return getClassId.value;
    },
    fetchSetting: {
      // 接口返回的表单数据字段名称
      listField: 'listDocQuality',
    },
    columns: getClassColumns(),
    showTableSetting: true,
    bordered: true,
    showIndexColumn: false,
    canResize: false,
    actionColumn: {
      width: 80,
      title: t('common.action'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
  });

  // 新增类属性
  const [registerClassPropModal, { openModal: openClassPropModal }] = useModal();
  // 属性组定义
  const [registerAttrGroupModal, { openModal: openAttrGroupModal }] = useModal();
  // 属性页定义
  const [registerAttrDefineModal, { openModal: openAttrDefineModal }] = useModal();
</script>

<style lang="less" scoped>
  ::v-deep(.ant-upload-list) {
    display: none !important;
  }
</style>
